//
//  OptionalViewController.swift
//  test_swift
//
//  Created by fangyuan ding on 2021/5/31.
//

import UIKit

class OptionalViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let name : String? = nil

        let arr = ["jack","uzi","godV","rookie"]
        func getObj(index:Int) -> String?{
            if index<0 || index >= arr.count {
                return nil
            }else{
                return arr[index]
            }
        }

        print(name as Any)
        print(getObj(index: 3) as Any)
        /*
        nil
        Optional("rookie")
        */
        
        let num = Int("123")
        print(num as Any)//Optional(123)

        if let num = Int("123"){
            print("num:",num)//num: 123

        }else{
            print("字符串转换失败")
        }
        if let a = Int("12") {
            if let b = Int("44") {
                if a < b && b < 100 {
                    print("\(a) < \(b) < 100")
                }
            }
        }

        //等同于

        if let a = Int("12"),
           let b = Int("44"),
            a < b && b < 100{
            print("\(a) < \(b) < 100")

        }
        
        //遍历数组，进行累加，如果遇到非数字，停止遍历
        let strs = ["1","2","-3","3","4","5",]
        var index:Int = 0
        var sum:Int = 0


        while
            index < strs.count,
            let obj = Int(strs[index]){
                sum += obj
                index += 1
        }
        print("sum:",sum)//12
        
        
        let a: Int? = 1
        let b: Int? = 2
        let c: Int = 3

        let d: Int? = nil

        print(a ?? b, a ?? c, d ?? b) //Optional(1) 1 Optional(2)

        let v1:Int? = nil
        let v2:Int? = 2

        if let c = v1 ?? v2{
            print(c)
        }
        //类似于 if v1 != nil || v2 != nil
        
        let v3:Int? = nil
        let v4:Int? = 2
        if let c = v3,
           let d = v4{
            print("result_c:",c)
            print("result_d:",d)

        }
        //隐式解包
        let num1 :Int! = 1  //虽然是隐式解包，但其仍是可选项
        let num2 :Int = num1 //隐式解包可以直接赋值给Int类型

        if let k = num1 {
            print(k)
        }else{
            print("nil")
        }

    }
    


}
